package com.barradata.app0624.modules.idcard

import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.View
import com.barradata.BuildConfig
import com.barradata.R
import com.barradata.app0624.api.ApiService
import com.barradata.app0624.modules.camera.CameraActivity
import com.barradata.app0624.modules.camera.CameraCallbackEvent
import com.barradata.app0624.modules.web.EventType
import com.barradata.app0624.modules.web.WebCallbackEvent
import com.barradata.common.base.BaseActivity
import com.barradata.common.rxbinding.clickV
import com.barradata.common.rxbus.RxBus
import com.barradata.common.utils.ToastUtils
import com.barradata.common.view.AlertDialogFragment
import com.example.hfiveandaplication.bean.IdentityData
import com.example.hfiveandaplication.view.ShootingDialog
import com.squareup.picasso.Callback.EmptyCallback
import com.squareup.picasso.Picasso
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.idcard_activity.*
import java.io.File


class IdCardActivity : BaseActivity() {
    companion object {
        private val REQUEST_PERMISSION = arrayOf(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)

        fun actionStart(context: Context) {
            val intent = Intent(context, IdCardActivity::class.java)
            context.startActivity(intent)
        }
    }

    private var identityBean: IdentityData.IdentityBean? = null
    private var idcardImage: IdentityData.ImageInfoBean? = null
    private var idcardWithPortraitImage: IdentityData.ImageInfoBean? = null
    private val rxPermissions = RxPermissions(this)
    private var isFirstClick = true


    override fun getLayoutId() = R.layout.idcard_activity

    override fun initView() {
        setupActionBar(toolbar)
//        requestPermission()
        setupButtons()
        registerCameraEventCallback()
    }

    private fun checkPermission(): Boolean {
        if (isFirstClick) {
            isFirstClick = false
            val shootingDialog = ShootingDialog(this, getStringResource(R.string
                    .auth_id_card_shopting_title))
            shootingDialog.show()
            shootingDialog.setOnClickListener {
                requestPermission()
                shootingDialog.hide()
            }
            return false
        }
        REQUEST_PERMISSION.iterator().forEach {
            if (!rxPermissions.isGranted(it)) {
                requestPermission()
                return false
            }
        }
        return true
    }

    private fun requestPermission() {
        rxPermissions.requestEachCombined(*REQUEST_PERMISSION).subscribe {
            if (it.granted) {
                return@subscribe
            }
            val singleButtonAction: () -> Unit
            if (it.shouldShowRequestPermissionRationale) {
                singleButtonAction = { requestPermission() }
            } else {
                singleButtonAction = { go2Setting() }
            }
            ToastUtils.showShort(R.string.get_permission_failure_hint)
            AlertDialogFragment.create(singleButtonAction, null)
                    .setTitle(getString(R.string.get_permission_failure_hint))
                    .show(this)
        }.autoClean()
    }

    private fun go2Setting() {
        val localIntent = Intent()
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        localIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
        localIntent.data = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null)
        startActivity(localIntent)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        RxBus.post(WebCallbackEvent(EventType.FROM_CANCEL))
    }


    private fun setupButtons() {
        idcard_front_iv.clickV()
                .filter { checkPermission() }
                .subscribe {
                    identityBean = null
                    idcardImage = null
                    CameraActivity.actionStart(this, ApiService.UploadImageType.ID_CARD)
                }.autoClean()
        idcard_with_portrait_iv.clickV()
                .filter { checkPermission() }
                .subscribe {
                    idcardWithPortraitImage = null
                    CameraActivity.actionStart(this, ApiService.UploadImageType.ID_CARD_WITH_PORTRAIT)
                }.autoClean()
        next_button.clickV()
                .filter { checkFormData(true) }
                .subscribe {
                    requestImageCompare()
                }.autoClean()
    }

    private fun requestImageCompare() {
        ApiService.imageCompare(idcardImage!!.imagePath, idcardWithPortraitImage!!.imagePath)
                .doOnSubscribe { showLoadingView() }
                .doFinally { dismissLoadingView() }
                .subscribe({
                    if (it.data.isCompareStatus) {
                        IdCardConfirmActivity.actionStart(this, it.data.pass, identityBean!!, idcardImage!!, idcardWithPortraitImage!!)
                        finish()
                    } else {
                        ToastUtils.showShort(it.message)
                    }
                }, {
                    it.printStackTrace()
                    ToastUtils.showShort(R.string.network_error)
                }).autoClean()
    }


    private fun registerCameraEventCallback() {
        RxBus.toObservable(CameraCallbackEvent::class.java)
                .filter { listOf(ApiService.UploadImageType.ID_CARD, ApiService.UploadImageType.ID_CARD_WITH_PORTRAIT).contains(it.photoType) }
                .subscribe {
                    uploadPhotoFile(it.photoFile, it.photoType)
                }.autoClean()
    }

    private fun updatePhotoView() {
        if (idcardImage != null) {
            // 用户上传的身份证照片未识别成功，此处进行拦截并提示
            // TODO: 识别成功率太低，弃用
//            if (identityBean == null || identityBean?.realName.isNullOrEmpty() || identityBean?.identityCardNum.isNullOrEmpty() ) {
//                ToastUtils.showShort(R.string.auth_id_card_positive_hint)
//                return
//            }
            // 身份证照片 OCR 识别成功时，回显照片
            Picasso.get().load(idcardImage!!.imageUrl).into(idcard_front_iv, object : EmptyCallback() {
                override fun onSuccess() {
                    hint1_group.visibility = View.GONE
                    idcard_front_iv.isEnabled = false
                    updateNextButton()
                }
            })
        }
        if (idcardWithPortraitImage != null) {
            Picasso.get().load(idcardWithPortraitImage!!.imageUrl).into(idcard_with_portrait_iv, object : EmptyCallback() {
                override fun onSuccess() {
                    hint2_group.visibility = View.GONE
                    idcard_with_portrait_iv.isEnabled = false
                    updateNextButton()
                }
            })
        }
    }

    private fun uploadPhotoFile(file: File, type: ApiService.UploadImageType) {
        ApiService.uploadImage(type, file).subscribe({
            logD(it.message)
            if (it.isRel) {
                if (it.data.imageInfo.fileType == ApiService.UploadImageType.ID_CARD.ordinal) {
                    idcardImage = it.data.imageInfo
                    identityBean = it.data.identity
                }
                if (it.data.imageInfo.fileType == ApiService.UploadImageType.ID_CARD_WITH_PORTRAIT.ordinal) {
                    idcardWithPortraitImage = it.data.imageInfo
                }
                updatePhotoView()
            } else {
                ToastUtils.showShort(it.message)
            }

        }, {
            showSnackBarShort(it.message.toString())
            it.printStackTrace()
        }).autoClean()

    }

    private fun checkFormData(isShowToast: Boolean): Boolean {
        if (idcard_front_iv.drawable == null) {
            if (isShowToast) {
                ToastUtils.showShort(R.string.auth_id_card_positive_hint)
            }
            return false
        }
        if (idcard_with_portrait_iv.drawable == null) {
            if (isShowToast) {
                ToastUtils.showShort(R.string.auth_id_card_positive_half_body_hint)
            }
            return false
        }
//        if (null == identityBean) {
//            if (isShowToast) {
//                ToastUtils.showShort(R.string.auth_id_card_positive_hint)
//            }
//            return false
//        }
        if (null == idcardImage) {
            if (isShowToast) {
                ToastUtils.showShort(R.string.auth_id_card_positive_hint)
            }
            return false
        }
        if (null == idcardWithPortraitImage) {
            if (isShowToast) {
                ToastUtils.showShort(R.string.auth_id_card_positive_half_body_hint)
            }
            return false
        }
        return true
    }


    private fun updateNextButton() {
        if (checkFormData(false)) {
            next_button.setBackgroundResource(R.drawable.button_bg_normal)
        } else {
            next_button.setBackgroundResource(R.drawable.button_bg_disable)
        }
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0, R.anim.fade_out)
    }
}
